"""
IP地址检测工具
显示所有网络接口的IP地址
"""
import socket


def get_all_ips():
    """获取所有IP地址"""
    print("=" * 60)
    print("检测所有网络接口IP地址")
    print("=" * 60)
    
    try:
        hostname = socket.gethostname()
        print(f"\n主机名: {hostname}\n")
        
        # 获取所有IP地址
        ip_list = socket.gethostbyname_ex(hostname)[2]
        
        print("所有检测到的IP地址:")
        print("-" * 60)
        
        lan_ips = []
        other_ips = []
        
        for idx, ip in enumerate(ip_list, 1):
            # 判断是否为局域网IP
            if ip.startswith('192.168.'):
                print(f"{idx}. {ip}  [LAN IP - 192.168.x.x] [OK] RECOMMENDED")
                lan_ips.append(ip)
            elif ip.startswith('10.'):
                print(f"{idx}. {ip}  [LAN IP - 10.x.x.x] [OK]")
                lan_ips.append(ip)
            elif ip.startswith('172.'):
                if int(ip.split('.')[1]) >= 16 and int(ip.split('.')[1]) <= 31:
                    print(f"{idx}. {ip}  [LAN IP - 172.16-31.x.x] [OK]")
                    lan_ips.append(ip)
                else:
                    print(f"{idx}. {ip}  [Other IP]")
                    other_ips.append(ip)
            elif ip == '127.0.0.1':
                print(f"{idx}. {ip}  [Loopback] [WARNING] Cannot use for network")
            else:
                print(f"{idx}. {ip}  [Other IP]")
                other_ips.append(ip)
        
        print("\n" + "=" * 60)
        print("Analysis Result")
        print("=" * 60)
        
        if lan_ips:
            print(f"\n[OK] Found {len(lan_ips)} LAN IP(s):")
            for ip in lan_ips:
                print(f"   -> {ip}")
            
            print(f"\n[RECOMMENDED] Use this IP: {lan_ips[0]}")
            print("\nDescription:")
            if lan_ips[0].startswith('192.168.'):
                print("   - Standard home/office LAN IP")
                print("   - Usually assigned by router")
                print("   - Suitable for WiFi or wired LAN")
        else:
            print("\n[ERROR] No LAN IP found")
            print("\nPossible reasons:")
            print("   1. Not connected to WiFi or wired network")
            print("   2. Network adapter disabled")
            print("   3. Only using virtual network (e.g., VPN)")
            
            if other_ips:
                print(f"\nOther available IP: {other_ips[0]}")
        
        # UDP method
        print("\n" + "-" * 60)
        print("Alternative method (UDP connection test):")
        print("-" * 60)
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            udp_ip = s.getsockname()[0]
            s.close()
            print(f"IP via UDP method: {udp_ip}")
            
            if udp_ip in lan_ips:
                print("[OK] Matches LAN IP")
            else:
                print("[WARNING] Does not match LAN IP")
        except Exception as e:
            print(f"UDP method failed: {e}")
        
    except Exception as e:
        print(f"\nError: {e}")
    
    print("\n" + "=" * 60)
    print("Usage Tips")
    print("=" * 60)
    print("\n1. Use the recommended IP when creating a room")
    print("2. Make sure all devices are on the same WiFi")
    print("3. If it shows 127.0.0.1, check network connection")
    print("=" * 60)


if __name__ == "__main__":
    try:
        get_all_ips()
    except Exception as e:
        print(f"Error: {e}")
    finally:
        print("\nPress Enter to exit...")
        try:
            input()
        except:
            pass

